package com.common.service;


import java.io.File;
import java.util.Date;

import javax.annotation.PostConstruct;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.JSONObject;
import com.common.util.AESUtil;
import com.common.util.DateFormatUtil;
import com.common.util.EnvironmentUtil;

import cn.hutool.core.util.RuntimeUtil;
import lombok.extern.slf4j.Slf4j;

//@Configuration
@Slf4j
public class LoadLicence {

	@Value("${system.licence.path:../../licence}")
	private String licenceFilePath;
	
	@PostConstruct
	public void validate() {
		if(EnvironmentUtil.isDevEnvi()) {
			return ;
		}
		File file=new File(licenceFilePath);
		String filePath=file.getAbsolutePath();
		try {
			filePath=file.getCanonicalPath();			
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!file.exists()) {
			log.error("授权文件licence在目录{}不存在",filePath);
			System.exit(1);
		}
		try {
			byte[] fileByte=FileUtils.readFileToByteArray(file);
			String cryJson=new String(fileByte, "utf-8");
			String decryJson=AESUtil.decrypt(cryJson, LoadLicence.class.getSimpleName());
			LicenceModel model=JSONObject.parseObject(decryJson, LicenceModel.class);
			String md5Value=model.getMd5();
			model.setMd5(null);
			String mdhJson=JSONObject.toJSONString(model);
			String md5Value2=DigestUtils.md5Hex(mdhJson);
			if(!md5Value.equals(md5Value2)) {
				log.error("授权文件licence在目录{}非法被篡改,请重新申请",filePath);
				System.exit(1);
			}
			boolean isTemp=false;
			String fileName="授权文件";
			String uuid=model.getOrgCode();
			if(StringUtils.isEmpty(uuid)) {
				fileName="临时授权文件";
				isTemp=true;
			}
			Date expireDate=model.getExpireDate();
			if(expireDate==null||expireDate.before(new Date())) {
				log.error(fileName+"licence在目录{}已过期,请重新申请",filePath);
				System.exit(1);
			}
			if(!isTemp) {
				String localUUID=RuntimeUtil.execForLines("wmic csproduct get UUID").get(2).trim();
				if(!uuid.equalsIgnoreCase(localUUID)) {
					log.error(fileName+"licence在目录{}和本地机器不匹配,请提交设备UUID重新申请",filePath);
					System.exit(1);
				}
			}
			log.info(fileName+"授权验证通过,有效期至"+DateFormatUtil.format(expireDate,DateFormatUtil.PATTERN_DEFAULT_ON_DATE));
		} catch (Exception e) {
			log.error("授权文件licence在目录{}解析异常,请重新申请",filePath);
			System.exit(1);
		}
	}
	
	static class LicenceModel {
		
		private String orgCode;
		
		private Date expireDate;

		private String md5;
		
		public String getOrgCode() {
			return orgCode;
		}

		public Date getExpireDate() {
			return expireDate;
		}

		public void setOrgCode(String orgCode) {
			this.orgCode = orgCode;
		}

		public void setExpireDate(Date expireDate) {
			this.expireDate = expireDate;
		}

		public String getMd5() {
			return md5;
		}

		public void setMd5(String md5) {
			this.md5 = md5;
		}
	}
}
